package com.zqh.web.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.volcengine.ark.runtime.model.completion.chat.ChatMessage;
import com.volcengine.ark.runtime.model.completion.chat.ChatMessageRole;
import com.zqh.web.common.ErrorCode;
import com.zqh.web.exception.BusinessException;
import com.zqh.web.manager.AiManager;
import com.zqh.web.mapper.MsgMapper;
import com.zqh.web.model.dto.chat.ChatMsg;
import com.zqh.web.model.dto.chat.ChatRoomMsgList;
import com.zqh.web.model.entity.Msg;
import com.zqh.web.service.ChatService;
import com.zqh.web.utils.ReadResourceUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class ChatServiceImpl implements ChatService {


    private final AiManager aiManager;

    private static final String START_KEYWORD = "开始";

    private final MsgMapper msgMapper;

    @Override
    public String doChat(ChatMsg chatMsg) {
        String messageContent = chatMsg.getMessage();
        Long roomId = chatMsg.getRoomId();

        // 读取系统预设提示
        String path = ReadResourceUtils.getInputResourcePath() + "static/prompt/systemPrompt.txt";
        String systemPrompt = FileUtil.readUtf8String(path);

        if (messageContent.contains(START_KEYWORD)) {
            // 开始游戏：清空旧消息并初始化系统消息
            LambdaQueryWrapper<Msg> deleteWrapper = new LambdaQueryWrapper<>();
            deleteWrapper.eq(Msg::getRoomId, roomId);
            // 如果查寻不为空不为空，再删除
            if (CollUtil.isNotEmpty(msgMapper.selectList(deleteWrapper))) {
                msgMapper.delete(deleteWrapper);
            }

            // 插入系统消息
            Msg systemMsg = Msg.builder()
                    .roomId(roomId)
                    .role(ChatMessageRole.SYSTEM.value())
                    .content(systemPrompt)
                    .build();

            msgMapper.insert(systemMsg);
        } else {
            // 非开始消息：确保房间已存在消息
            Long count = msgMapper.selectCount(new LambdaQueryWrapper<Msg>().eq(Msg::getRoomId, roomId));
            if (count == 0) {
                throw new BusinessException(ErrorCode.GAME_ERROR, "请先发送“开始游戏”");
            }
        }

        // 插入当前用户消息
        Msg userMsg = Msg.builder()
                .roomId(roomId)
                .role(ChatMessageRole.USER.value())
                .content(messageContent)
                .build();
        msgMapper.insert(userMsg);

        // 获取完整对话历史（按时间排序）
        LambdaQueryWrapper<Msg> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Msg::getRoomId, roomId)
                .orderByAsc(Msg::getCreateTime);
        List<Msg> msgList = msgMapper.selectList(queryWrapper);

        // 转换为ChatMessage列表
        List<ChatMessage> messages = msgList.stream()
                .map(msg -> ChatMessage.builder()
                        .role(ChatMessageRole.USER)
                        .content(msg.getContent())
                        .build())
                .collect(Collectors.toList());

        // 调用AI获取回复
        String answer = aiManager.doChat(messages);

        // 插入AI回复
        Msg assistantMsg = Msg.builder()
                .roomId(roomId)
                .role(ChatMessageRole.ASSISTANT.value())
                .content(answer)
                .build();
        msgMapper.insert(assistantMsg);

        // 游戏结束处理
        if (answer.contains("结束")) {
            msgMapper.delete(new LambdaQueryWrapper<Msg>().eq(Msg::getRoomId, roomId));
        }

        return answer;
    }


    /**
     * 获取聊天室消息列表
     * 此方法首先查询所有消息记录，然后按 roomId 分组，
     * 将每个聊天室的消息封装成 ChatRoomMsgList 对象，
     * 最后返回包含所有聊天室消息列表的集合
     * @return 包含所有聊天室消息列表的集合
     */
    public List<ChatRoomMsgList> getChatRoomList() {
        // 初始化聊天室消息列表集合
        List<ChatRoomMsgList> chatRoomList = new ArrayList<>();

        // 一次性查询所有消息，避免 N+1 查询
        List<Msg> msgList = msgMapper.selectList(null);

        // 使用 Map 按 roomId 分组
        Map<Long, List<Msg>> roomMsgMap = new HashMap<>();
        for (Msg msg : msgList) {
            roomMsgMap.computeIfAbsent(msg.getRoomId(), k -> new ArrayList<>()).add(msg);
        }

        // 遍历每个聊天室的消息
        for (Map.Entry<Long, List<Msg>> entry : roomMsgMap.entrySet()) {
            Long roomId = entry.getKey();
            List<Msg> msgs = entry.getValue();

            // 创建 ChatRoomMsgList 对象并设置 roomId
            ChatRoomMsgList chatRoomMsgList = new ChatRoomMsgList();
            chatRoomMsgList.setRoomId(roomId);

            // 初始化聊天消息列表
            List<ChatMessage> chatMessages = new ArrayList<>();
            for (Msg msg : msgs) {
                ChatMessage chatMessage;

                // 根据消息的角色生成对应的 ChatMessage 对象
                if (msg.getRole() == null) {
                    // 处理 null 角色
                    chatMessage = ChatMessage.builder()
                            .role(ChatMessageRole.ASSISTANT)
                            .content(msg.getContent())
                            .build();
                } else if ("user".equals(msg.getRole()) || "system".equals(msg.getRole())) {
                    // 注意："user" 和 "system" 都映射为 SYSTEM，需确认是否合理
                    chatMessage = ChatMessage.builder()
                            .role(ChatMessageRole.SYSTEM)
                            .content(msg.getContent())
                            .build();
                } else if ("assistant".equals(msg.getRole())) {
                    chatMessage = ChatMessage.builder()
                            .role(ChatMessageRole.ASSISTANT)
                            .content(msg.getContent())
                            .build();
                } else {
                    // 处理未知角色
                    chatMessage = ChatMessage.builder()
                            .role(ChatMessageRole.ASSISTANT)
                            .content(msg.getContent())
                            .build();
                    // 可选：记录日志提醒未知角色
                    // log.warn("Unknown role: {}", msg.getRole());
                }

                // 将生成的 ChatMessage 对象添加到聊天消息列表中
                chatMessages.add(chatMessage);
            }

            // 设置聊天室的消息列表并添加到聊天室消息列表集合中
            chatRoomMsgList.setMessageList(chatMessages);
            chatRoomList.add(chatRoomMsgList);
        }

        // 返回聊天室消息列表集合
        return chatRoomList;
    }


}
